package com.ynet.middleground.riskmanage.model.rizhaogang;


import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.*;

import javax.validation.Valid;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.riskmanage.bean.rizhaogang.RzgCustomsReleaseQueryReq;
import com.ynet.middleground.riskmanage.bean.rizhaogang.RzgFreezeUnfreezeReq;
import com.ynet.middleground.riskmanage.bean.rizhaogang.RizhaoPortGoodsTypeQueryReq;
import com.ynet.middleground.riskmanage.bean.rizhaogang.RzgGoodsInfoQueryReq;
import com.ynet.middleground.riskmanage.bean.rizhaogang.RzgNowCargoInfoQueryReq;
import com.ynet.middleground.riskmanage.common.SystemConstant;
import com.ynet.middleground.riskmanage.dao.RzgCustomsMapper;
import com.ynet.middleground.riskmanage.dao.RzgGoodsBoatInfoMapper;
import com.ynet.middleground.riskmanage.dao.RzgGoodsCargoInfoMapper;
import com.ynet.middleground.riskmanage.dao.*;
import com.ynet.middleground.riskmanage.dto.rizhaogang.RizhaoPortDockCompanyInfoDTO;
import com.ynet.middleground.riskmanage.dto.rizhaogang.RzgCustomsReleaseDTO;
import com.ynet.middleground.riskmanage.dto.rizhaogang.RizhaoPortGoodsTypeInfoDTO;
import com.ynet.middleground.riskmanage.dto.rizhaogang.RzgGoodsInfoDTO;
import com.ynet.middleground.riskmanage.dto.rizhaogang.RzgNowCargoInfoDTO;
import com.ynet.middleground.riskmanage.entity.rizhaogang.RzgCustoms;
import com.ynet.middleground.riskmanage.entity.rizhaogang.RzgGoodsBoatInfo;
import com.ynet.middleground.riskmanage.entity.rizhaogang.RzgGoodsCargoInfo;
import com.ynet.middleground.riskmanage.entity.rizhaogang.*;
import com.ynet.middleground.riskmanage.external.rizhaogang.RzgApiHelper;
import com.ynet.middleground.riskmanage.external.rizhaogang.RzgUriEnum;
import com.ynet.middleground.riskmanage.utils.BeanUtil;


import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * @ClassName RiZhaoGangModel
 * @Description 日照港服务处理逻辑
 * @Author songyf
 * @Date 2020/10/16 14:32
 * @Version 1.0
 */
@Component
public class RiZhaoGangModel {

    @Autowired
    private RzgApiHelper rzgApiHelper;

    @Autowired
    private DozerBeanMapper dozerBeanMapper;

    @Autowired
    private RzgGoodsBoatInfoMapper rzgGoodsBoatInfoMapper;

    @Autowired
    private RzgGoodsCargoInfoMapper rzgGoodsCargoInfoMapper;
    
    @Autowired
    private RzgCustomsMapper rzgCustomsMapper;
    
    @Autowired
    RizhaoPortDockCompanyInfoMapper rizhaoPortDockCompanyInfoMapper;

    @Autowired
    RizhaoPortGoodsTypeInfoMapper rizhaoPortGoodsTypeInfoMapper;
    
    @Autowired
    RzgNowCargoInfoMapper rzgNowCargoInfoMapper;
    
    @Autowired
    RizhaoPortFreezeInfoMapper rizhaoPortFreezeInfoMapper;
    
    /**
     * 货物信息查询
     *
     * @param req 查询货物信息请求信息
     * @return 货物信息传输对象
     * @author songyf
     */
    @Transactional(rollbackFor = Exception.class)
    public RzgGoodsInfoDTO getGoodsInfo(@Valid RzgGoodsInfoQueryReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("serialNo", req.getTraceId());
        params.put("gsdm", req.getCompanyCode());
        params.put("wtr", req.getWorkentrust());
        params.put("hwmch", req.getGoodsType());
        params.put("chm", req.getShipNameCh());
        params.put("hth", req.getContractNo());
        JSONObject apiResult = rzgApiHelper.sendApi(RzgUriEnum.PORT_CARGO, params, req);
        String code = apiResult.getString("resultCode");
        String message = apiResult.getString("resultMsg");
        String msg = apiResult.getString("msg");
        if(StringUtils.isNotEmpty(msg)) {
            throw new BusinessException(msg, String.valueOf(code));
        }
        if(StringUtils.isNotEmpty(message)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        Map<String, String> map = new HashMap<>();
        //进行key值转换
        map.put("tzdh", "shipNoticeOrder");
        map.put("tzdid", "shipNoticeId");
        map.put("zhwchm", "shipNameCh");
        map.put("ywchm", "shipNameEn");
        map.put("hc", "voyageNumber");
        map.put("dlgsmch", "agencyCompany");
        map.put("chbzht", "state");
        map.put("zgzht", "departure");
        map.put("mb", "trade");
        map.put("zhxlb", "loadUnload");
        map.put("zhxjh", "loadUnloadPlan");
        map.put("pz", "stowage");
        map.put("jjsh", "handover");
        map.put("chfgmch", "leavePort");
        map.put("ddgmch", "arrivePort");
        map.put("gsmch", "companyName");
        map.put("lrry", "declarant");
        map.put("gkf", "portFee");
        map.put("dcf", "storageFee");
        map.put("tjrq", "reportDate");
        map.put("jhl", "planNumber");
        map.put("zhl", "shipmentNumber");
        map.put("fyTime", "shipmentTime");
        map.put("zzh", "railTransNumber");
        map.put("rk", "todayIn");
        map.put("chk", "todayOut");
        map.put("drkc", "timeStock");
        apiResult = BeanUtil.changeJsonObj(apiResult, map);
        RzgGoodsCargoInfo rzgGoodsCargoInfo = apiResult.getJSONObject("cargoInfo").toJavaObject(RzgGoodsCargoInfo.class);
        RzgGoodsBoatInfo rzgGoodsBoatInfo = apiResult.getJSONObject("boatInfo").toJavaObject(RzgGoodsBoatInfo.class);
        rzgGoodsCargoInfo.setSerialNo(req.getTraceId());
        rzgGoodsBoatInfo.setSerialNo(req.getTraceId());
        LambdaQueryWrapper<RzgGoodsBoatInfo> queryWrapper2 = new LambdaQueryWrapper<RzgGoodsBoatInfo>();
        queryWrapper2.eq(RzgGoodsBoatInfo::getVoyageNumber,rzgGoodsBoatInfo.getVoyageNumber());
//        rzgGoodsBoatInfoMapper.delete(queryWrapper2);
        LambdaQueryWrapper<RzgGoodsCargoInfo> queryWrapper3 = new LambdaQueryWrapper<RzgGoodsCargoInfo>();
        queryWrapper3.eq(RzgGoodsCargoInfo::getCargokey,rzgGoodsCargoInfo.getCargokey());
//        rzgGoodsCargoInfoMapper.delete(queryWrapper3);
        if(rzgGoodsBoatInfoMapper.selectCount(queryWrapper2)>0){
            rzgGoodsBoatInfo.setSerialNo(rzgGoodsBoatInfoMapper.selectList(queryWrapper2).get(0).getSerialNo());
            rzgGoodsBoatInfo.setModifiedBy(req.getOperationUserId());
            rzgGoodsBoatInfo.setGmtModified(LocalDateTime.now());
            rzgGoodsBoatInfoMapper.update(rzgGoodsBoatInfo,queryWrapper2);
        }else {
            BeanUtil.setGenericInfo(rzgGoodsBoatInfo, req);
            rzgGoodsBoatInfoMapper.insert(rzgGoodsBoatInfo);
        }
        rzgGoodsCargoInfo.setGoodsType(req.getGoodsType());
        if(rzgGoodsCargoInfoMapper.selectCount(queryWrapper3)>0){
            if(StringUtils.isNotBlank(rzgGoodsCargoInfo.getCargokey())){
                rzgGoodsCargoInfo.setModifiedBy(req.getOperationUserId());
                rzgGoodsCargoInfo.setGmtModified(LocalDateTime.now());
                rzgGoodsCargoInfoMapper.update(rzgGoodsCargoInfo,queryWrapper3);
            }
//            else{
//                BeanUtil.setGenericInfo(rzgGoodsCargoInfo, req);
//                rzgGoodsCargoInfoMapper.insert(rzgGoodsCargoInfo);
//            }
        }else{
            BeanUtil.setGenericInfo(rzgGoodsCargoInfo, req);
            rzgGoodsCargoInfoMapper.insert(rzgGoodsCargoInfo);
        }
        RzgGoodsInfoDTO rzgGoodsInfoDTO = apiResult.toJavaObject(RzgGoodsInfoDTO.class);
        return rzgGoodsInfoDTO;
    }

    /**查询码头公司信息**/
    @Transactional(rollbackFor = Exception.class)
    public List<RizhaoPortDockCompanyInfoDTO> getCompanyInfo(BaseReqObj req) {
        //组装接口输入参数
        Map<String, Object> params = new HashMap<>(1);
        params.put("serialNo", req.getTraceId());
        //正常调用接口
        JSONObject apiResult = rzgApiHelper.sendApi(RzgUriEnum.WHARF_COMPANY, params, req);
        //测试数据
        //JSONObject apiResult  = JSONArray.parseObject("{\"serialNo\":\"100\",\"resultCode\":0,\"resultMsg\":\"\",\"zygsList\":[{\"gsdm\":\"00\",\"gsmch\":\"集团\"},{\"gsdm\":\"11\",\"gsmch\":\"一公司\"},{\"gsdm\":\"12\",\"gsmch\":\"二公司\"},{\"gsdm\":\"13\",\"gsmch\":\"三公司\"},{\"gsdm\":\"15\",\"gsmch\":\"客箱公司\"},{\"gsdm\":\"14\",\"gsmch\":\"日青公司\"},{\"gsdm\":\"25\",\"gsmch\":\"日港裕廊\"},{\"gsdm\":\"21\",\"gsmch\":\"岚山公司\"},{\"gsdm\":\"16\",\"gsmch\":\"油品公司\"}]}");
        String code = apiResult.getString("resultCode");
        String message = apiResult.getString("resultMsg");
        String msg = apiResult.getString("msg");
        if(StringUtils.isNotEmpty(msg)) {
            throw new BusinessException(msg, String.valueOf(code));
        }
        if(StringUtils.isNotEmpty(message)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        JSONArray companyArray = apiResult.getJSONArray("zygsList");

        Map<String, String> map = new HashMap<>(2);
        //进行key值转换
        map.put("gsdm", "companyCode");
        map.put("gsmch", "companyName");
        companyArray = BeanUtil.changeJsonArr(companyArray, map);

        List<RizhaoPortDockCompanyInfo> companyInfos = new ArrayList<>();

        if (companyArray != null) {
            companyInfos = companyArray.toJavaList(RizhaoPortDockCompanyInfo.class);
            for (RizhaoPortDockCompanyInfo companyInfo : companyInfos) {
                BeanUtil.setGenericInfo(companyInfo, req);
                companyInfo.setSerialNo(req.getTraceId());
            }
            //先删除数据
            rizhaoPortDockCompanyInfoMapper.deleteAllCompanyInfo();

            //在插入数据
            rizhaoPortDockCompanyInfoMapper.insertBatchCompanyInfo(companyInfos);
        }
        List<RizhaoPortDockCompanyInfoDTO> companyInfoDTOS =
                BeanUtil.mapList(dozerBeanMapper, companyInfos, RizhaoPortDockCompanyInfoDTO.class);

        return companyInfoDTOS;
    }

    /**
     * 海关放行信息查询
     * @author songyf
     * @param req 查询海关放行信息请求信息
     * @return 海关放行信息传输对象
     */
    public List<RzgCustomsReleaseDTO> getCustomsRelease(@Valid RzgCustomsReleaseQueryReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("entryId", req.getEntryId());
        params.put("serialNo", req.getTraceId());
        JSONObject apiResult = rzgApiHelper.sendApi(RzgUriEnum.HG_INFO, params, req);
        String code = apiResult.getString("resultCode");
        String message = apiResult.getString("resultMsg");
        String msg = apiResult.getString("msg");
        if(StringUtils.isNotEmpty(msg)) {
            throw new BusinessException(msg, String.valueOf(code));
        }
        if(StringUtils.isNotEmpty(message)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        JSONObject hgInfo = apiResult.getJSONObject("hgInfo");
        RzgCustoms rzgCustoms = hgInfo.toJavaObject(RzgCustoms.class);
 //       RzgCustoms rzgCustoms = dozerBeanMapper.map(apiResult.get("hgInfo"), RzgCustoms.class);
        rzgCustoms.setSerialNo(req.getTraceId());
        LambdaQueryWrapper<RzgCustoms> queryWrapper = new LambdaQueryWrapper<RzgCustoms>();
        queryWrapper.eq(RzgCustoms::getEntryId,rzgCustoms.getEntryId());
//        rzgCustomsMapper.delete(queryWrapper);
//        BeanUtil.setGenericInfo(rzgCustoms, req);
//        rzgCustomsMapper.insert(rzgCustoms);
        if(rzgCustomsMapper.selectCount(queryWrapper)>0){
            rzgCustoms.setGmtModified(LocalDateTime.now());
            rzgCustoms.setModifiedBy(req.getOperationUserId());
            rzgCustomsMapper.update(rzgCustoms,queryWrapper);
        }else{
            BeanUtil.setGenericInfo(rzgCustoms, req);
            rzgCustomsMapper.insert(rzgCustoms);
        }

        Map<String, String> map = new HashMap<>();
        map.put("entryId", "customsNo");
        map.put("passPackNo", "inNumber");
        map.put("gUnit", "unitNum");
        map.put("packNo", "inNum");
        map.put("netWt", "weight");
        map.put("grossWt", "toWeight");
        map.put("rDate", "toDate");
        map.put("hgFlag", "customsState");
        hgInfo = BeanUtil.changeJsonObj(hgInfo, map);
        RzgCustomsReleaseDTO rzgCustomsReleaseDTO = hgInfo.toJavaObject(RzgCustomsReleaseDTO.class);

        //组成List返回
        List<RzgCustomsReleaseDTO> returnMsg = new ArrayList<RzgCustomsReleaseDTO>(1);
        returnMsg.add(rzgCustomsReleaseDTO);
        return returnMsg;
    }

    /**查询货物种类信息**/
    public List<RizhaoPortGoodsTypeInfoDTO> getGoodsTypeInfo(RizhaoPortGoodsTypeQueryReq req){
        //组装接口输入参数
        Map<String, Object> params = new HashMap<>(3);
        params.put("serialNo", req.getTraceId());
        params.put("gsdm", req.getCompanyCode());
        params.put("xlmch", req.getGoodsTypeName());
        //正常调用接口
        JSONObject apiResult = rzgApiHelper.sendApi(RzgUriEnum.CARGO_TYPE, params, req);
        //测试数据
//        JSONObject apiResult  = JSONArray.parseObject("{\"serialNo\":\"101\",\"resultCode\":0,\"resultMsg\":\"\",\"cargoList\":[{\"cargokey\":\"\",\"chk\":0,\"drkc\":0,\"fyTime\":\"\",\"jhl\":0,\"jhzhl\":0,\"rk\":0,\"tjrq\":\"\",\"xldm\":\"00000900\",\"xlmch\":\"卡拉拉精粉\",\"zhl\":0,\"zzh\":0},{\"cargokey\":\"\",\"chk\":0,\"drkc\":0,\"fyTime\":\"\",\"jhl\":0,\"jhzhl\":0,\"rk\":0,\"tjrq\":\"\",\"xldm\":\"00000818\",\"xlmch\":\"乌精粉2.4.6.8舱\",\"zhl\":0,\"zzh\":0}]}");
        String code = apiResult.getString("resultCode");
        String message = apiResult.getString("resultMsg");
        String msg = apiResult.getString("msg");
        if(StringUtils.isNotEmpty(msg)) {
            throw new BusinessException(msg, String.valueOf(code));
        }
        if(StringUtils.isNotEmpty(message)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        //获取货物信息
        JSONArray goodsTypeArray = apiResult.getJSONArray("cargoList");

        Map<String, String> map = new HashMap<>(2);
        //进行key值转换
        map.put("xldm", "goodsTypeCode");
        map.put("xlmch", "goodsTypeName");
        goodsTypeArray = BeanUtil.changeJsonArr(goodsTypeArray, map);

        List<RizhaoPortGoodsTypeInfo> goodsTypeInfos = new ArrayList<>();
        if (goodsTypeArray.size()>0) {
            goodsTypeInfos = goodsTypeArray.toJavaList(RizhaoPortGoodsTypeInfo.class);
            for (RizhaoPortGoodsTypeInfo goodsTypeInfo : goodsTypeInfos) {
                BeanUtil.setGenericInfo(goodsTypeInfo, req);
                goodsTypeInfo.setSerialNo(req.getTraceId());
                goodsTypeInfo.setCompanyCode(req.getCompanyCode());

            }
            //先删除数据
            rizhaoPortGoodsTypeInfoMapper.deleteAllGoodsTypeInfo();

            //在插入数据
            rizhaoPortGoodsTypeInfoMapper.insertBatchGoodsTypeInfo(goodsTypeInfos);
        }
        List<RizhaoPortGoodsTypeInfoDTO> goodsTypeInfoDTOS =
                BeanUtil.mapList(dozerBeanMapper, goodsTypeInfos, RizhaoPortGoodsTypeInfoDTO.class);

        return goodsTypeInfoDTOS;
    }

    /**
     * 冻结、解冻港口货物
     * @author songyf
     * @param req 冻结、解冻港口货物请求信息
     * @return String
     */
    public Object freezeUnfreeze(@Valid RzgFreezeUnfreezeReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("serialNo", req.getTraceId());
        params.put("cargokey", req.getCargokey());
        params.put("typ", req.getOrder());
        params.put("weight", req.getWeight());
        RizhaoPortFreezeInfo rizhaoPortFreezeInfo = dozerBeanMapper.map(params, RizhaoPortFreezeInfo.class);
        BeanUtil.setGenericInfo(rizhaoPortFreezeInfo, req);
        rizhaoPortFreezeInfoMapper.insert(rizhaoPortFreezeInfo);
        JSONObject apiResult = rzgApiHelper.sendApi(RzgUriEnum.CONTROL_CARGO, params, req);
        String code = apiResult.getString("resultCode");
        String message = apiResult.getString("resultMsg");
        String msg = apiResult.getString("msg");
        rizhaoPortFreezeInfo.setResultCode(code);
        if(StringUtils.isNotEmpty(msg)) {
            rizhaoPortFreezeInfo.setResultMsg(msg);
            rizhaoPortFreezeInfo.updateById();
            throw new BusinessException(msg, String.valueOf(code));
        }
        if(StringUtils.isNotEmpty(message)) {
            rizhaoPortFreezeInfo.setResultMsg(message);
            rizhaoPortFreezeInfo.updateById();
            throw new BusinessException(message, String.valueOf(code));
        }
        rizhaoPortFreezeInfo.updateById();
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        return returnsResult;
    }

    /**
     * 货物实时动态查询
     * @author songyf
     * @param req 查询货物实时动态请求信息
     * @return 货物实时动态传输对象
     */
    public RzgNowCargoInfoDTO getNowCargoInfo(@Valid RzgNowCargoInfoQueryReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("cargokey", req.getCargokey());
        params.put("serialNo", req.getTraceId());
        JSONObject apiResult = rzgApiHelper.sendApi(RzgUriEnum.CARGO_INFO, params, req);
        String code = apiResult.getString("resultCode");
        String message = apiResult.getString("resultMsg");
        String msg = apiResult.getString("msg");
        if(StringUtils.isNotEmpty(msg)) {
            throw new BusinessException(msg, String.valueOf(code));
        }
        if(StringUtils.isNotEmpty(message)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        Map<String, String> map = new HashMap<>();
        //进行key值转换
        map.put("tjrq", "reportDate");
        map.put("jhl", "planNumber");
        map.put("zhl", "shipmentNumber");
        map.put("fyTime", "shipmentTime");
        map.put("zzh", "railTransNumber");
        map.put("rk", "todayIn");
        map.put("chk", "todayOut");
        map.put("drkc", "timeStock");
        apiResult = BeanUtil.changeJsonObj(apiResult, map);
        RzgNowCargoInfo rzgCustoms = apiResult.getJSONObject("cargoInfo").toJavaObject(RzgNowCargoInfo.class);
        rzgCustoms.setSerialNo(req.getTraceId());
        rzgCustoms.setCargokey(req.getCargokey());
        LambdaQueryWrapper<RzgNowCargoInfo> queryWrapper = new LambdaQueryWrapper<RzgNowCargoInfo>();
        queryWrapper.eq(RzgNowCargoInfo::getCargokey,rzgCustoms.getCargokey());
//        rzgNowCargoInfoMapper.delete(queryWrapper);
//        BeanUtil.setGenericInfo(rzgCustoms, req);
//        rzgNowCargoInfoMapper.insert(rzgCustoms);
        if(rzgNowCargoInfoMapper.selectCount(queryWrapper)>0){
            rzgCustoms.setModifiedBy(req.getOperationUserId());
            rzgCustoms.setGmtModified(LocalDateTime.now());
            rzgNowCargoInfoMapper.update(rzgCustoms,queryWrapper);
        }else{
            BeanUtil.setGenericInfo(rzgCustoms, req);
            rzgNowCargoInfoMapper.insert(rzgCustoms);
        }
        RzgNowCargoInfoDTO rzgCustomsReleaseDTO = apiResult.getJSONObject("cargoInfo").toJavaObject(RzgNowCargoInfoDTO.class);
        return rzgCustomsReleaseDTO;
    }
}
